package com.xinzhi.savingpot.userinfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xinzhi.savingpot.userinfo.mapper.IDaoRegister;
import com.xinzhi.savingpot.userinfo.service.IRegisterService;
import com.xinzhi.savingpot.util.*;
import com.xinzhi.savingpot.util.UserIdUtil.RandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private IDaoRegister iDaoRegister;
    @Autowired
    RedisUtil redisUtil;



    public String sendCode(String phone) {
        if(phone!=null){
            if (iDaoRegister.count(phone)==0){
                String authCode = NoteUtil.VCode();
                NoteUtil.send(phone,authCode);
                redisUtil.set(phone,authCode,300);
                return JSONObject.toJSONString(new BaseResponse(200,"发送成功"));
            } else {
                return JSONObject.toJSONString(new BaseResponse(400,"手机号已注册"));
            }
        }else{
            return JSONObject.toJSONString(new BaseResponse(400,"发送验证码失败"));
        }
    }



    @Override
    public String register(String phone, String password,String Code,String twoPassword) {
//        String phone1 = findPhone(phone);
        if(phone!=null){
            String oldCode = (String) redisUtil.get(phone);
            if (Code.equals(oldCode)){
                if(password.equals(twoPassword)){
                    String newPassword = MD5Util.stringMD5(password);
                    Integer as = Integer.valueOf(RandomNumberGenerator.generateNumber2());
                    int insert = iDaoRegister.insert(phone, newPassword,as);
                    if(insert>0){
                        return JSONObject.toJSONString(new BaseResponse(200,"注册成功"));
                    }else {
                        return JSONObject.toJSONString(new BaseResponse(200,"注册失败"));
                    }
                }else {
                    return JSONObject.toJSONString(new BaseResponse(400,"俩次密码输入有误"));
                }
            }else {
                return JSONObject.toJSONString(new BaseResponse(400,"手机号或验证码输入错误!"));
            }

        }else{
            return JSONObject.toJSONString(new BaseResponse(400,"请输入正确的手机号"));
        }

    }


}
